package com.chunlei.check.service;

import com.chunlei.check.utils.JedisUtil;
import com.chunlei.check.utils.UUID;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/11/9 19:59
 */
@Service
public class TokenService
{
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private static final String TOKEN_NAME = "token";
    private static final String TOKEN_PREFIX = "test-";

    @Autowired
    private JedisUtil jedisUtil;

    public String createToken()
    {
        String uuid = UUID.randomUUID().toString();
        StringBuilder token = new StringBuilder();
        token.append(TOKEN_PREFIX).append(uuid);
        jedisUtil.set(token.toString(), token.toString(), 60 * 60);
        return token.toString();
    }

    public void checkToken(HttpServletRequest request)
    {
        String token = request.getHeader(TOKEN_NAME);
        log.info("token:{}",token);
        if (StringUtils.isBlank(token))
        {
            // header中不存在token
            token = request.getParameter(TOKEN_NAME);
            if (StringUtils.isBlank(token))
            {// parameter中也不存在token
                log.error("token为空");
            }
        }

        if (!jedisUtil.exists(token))
        {
            log.error("token不存在");
        }

        Long del = jedisUtil.del(token);
        if (del <= 0)
        {
            log.error("token删除失败");
        }
    }
}
